<template>
  <div class="content">
    <div ref="content"
         :class="{'markdown__body':isMarked}"
         v-html="marked()"
         @click="handleDocumentClick($event)">
    </div>
  </div>
</template>

<script>
import marked from '@/utils/convertMarkDown'

export default {
  name: 'content-container',
  props: {
    isMarked: {
      type: Boolean,
      default: false
    },
    content: {
      type: String,
      default: ''
    },
    showImageViewer: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      previewSrcList: [],
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.buildMenuList()
    })
  },
  methods: {
    marked () {
      if (this.content === '') {
        return ''
      }
      if (this.isMarked) {
        return marked(this.content)
      }
      return this.content
    },
    handleDocumentClick (event) {
      if (event.target.nodeName === 'IMG') {
        if (this.showImageViewer) {
          const { target: { className, src } } = event;
          event.target.className = 'suspended';
          this.$imageViewer(src, this.previewSrcList).then(() => {
            event.target.className = '';
          });
        }
      }
    },
    buildMenuList () {
      console.log('刷新目录...');
      const content = this.$refs.content
      const h1s = content.getElementsByTagName("h1")
      const array = new Array()
      for (let i = 0; i < h1s.length; i++) {
        let h1 = h1s[i]
        array.push({
          'title': h1.innerText,
          'offsetTop': h1.offsetTop
        })
      }
      this.$emit('menuChange', array)
      this.buildImageList()
    },
    buildImageList () {
      const imgs = this.$refs.content.getElementsByTagName('img')
      for (let i = 0; i < imgs.length; i++) {
        this.previewSrcList.push(imgs[i].src)
      }
    },
  }
}
</script>

<style>
</style>